package cqrtplm.listener;

import cn.hutool.extra.spring.SpringUtil;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.annotion.CustomListenerField;
import com.hustcad.plm.pdm.workflow.model.constant.ProcessConstant;
import cqrtplm.service.FlowControlService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.el.FixedValue;

import java.math.BigInteger;

@Slf4j
@CustomListener(category = "润通" ,description = "发起者部门分支及成控溢价")
public class MixtureListener implements ExecutionListener {
    @CustomListenerField(description = "节点ID", defaultValue = "", required = true)
    private FixedValue nodeId;

    @CustomListenerField(description = "部门条件表达式", defaultValue = "", required = true)
    private FixedValue departmentCondition;
    @CustomListenerField(description = "条件", defaultValue = "", required = true)
    private FixedValue condition;


    @Override
    public void notify(DelegateExecution execution) {
        long start = System.currentTimeMillis();
        String workFlowContainerId = execution.getProcessInstanceBusinessKey();
        log.info("----------润通----发起者部门分支判断------开始------workFlowContainerId:{}----->>>", workFlowContainerId);

        if (StringUtils.isBlank(workFlowContainerId)) {
            workFlowContainerId = execution.getVariable(ProcessConstant.WORK_FLOW_CONTAINER_ID).toString();
        }

        try {
            String finalWorkFlowContainerId = workFlowContainerId;
            FlowControlService flowControlService = SpringUtil.getBean(FlowControlService.class);

            // 调用服务方法进行分支判断
            String nodeIdValue = nodeId != null ? nodeId.getExpressionText() : null;
            String departmentConditionValue = departmentCondition != null ? departmentCondition.getExpressionText() : null;

            flowControlService.checkMixture(
                    new BigInteger(finalWorkFlowContainerId),
                    nodeIdValue,
                    departmentConditionValue,
                    nodeId.getExpressionText(),
                    condition.getExpressionText()
            );


        }catch (Exception e) {
            log.error("发起者部门分支判断处理失败", e);
            throw new RuntimeException("发起者部门分支判断处理失败", e);
        }
    }
}
